using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using System.Reflection;
using System.Collections.Generic;
using Microsoft.SharePoint.Administration.Health;

namespace SDS.SPHealthAnalyzerRules.Delegation.Features.HealthRulesForDelegation
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("5e8c2b3f-4965-4865-8855-eea1a25d6ee4")]
    public class HealthRulesForDelegationEventReceiver : SPFeatureReceiver
    {

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
            LoggingService_Add();
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            HealthAnalyzerRules_Add();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            HealthAnalyzerRules_Remove();
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
            LoggingService_Remove();
        }

        // Uncomment the method below to handle the event raised when a feature is upgrading.

        //public override void FeatureUpgrading(SPFeatureReceiverProperties properties, string upgradeActionName, System.Collections.Generic.IDictionary<string, string> parameters)
        //{
        //}



        #region Private Methods



        private static void LoggingService_Add()
        {
            // remove any previously existing instances
            LoggingService.Unregister();

            // registration is handled automatically
            //LoggingService.Register();

            LoggingService.Write(LoggingService.Category_FeatureReceiver, Microsoft.SharePoint.Administration.TraceSeverity.Verbose, "Registered Logging: " + typeof(LoggingService).ToString(), new Guid());
        }
        private static void LoggingService_Remove()
        {

            LoggingService.Write(LoggingService.Category_FeatureReceiver, Microsoft.SharePoint.Administration.TraceSeverity.Verbose, "Unregistering Logging: " + typeof(LoggingService).ToString(), new Guid());

            LoggingService.Unregister();
        }


        
        // Source: http://msdn.microsoft.com/en-us/library/ee538252.aspx (enhanced with LINQ and LoggingService)
        private static void HealthAnalyzerRules_Add()
        {
            Assembly a = Assembly.GetExecutingAssembly();
            IDictionary<Type, Exception> exceptions = SPHealthAnalyzer.RegisterRules(a);

            if (exceptions != null)
            {
                string logEntry = String.Format("{0}: ", a.FullName);
                if (exceptions.Count == 0)
                {
                    logEntry += "All rules were registered.";
                }
                else
                {
                    logEntry += String.Join(", ", exceptions.Select(e => String.Format("Registration failed for type {0}. {1}", e.Key, e.Value.Message)).ToArray());
                }
                LoggingService.Write(LoggingService.Category_FeatureReceiver, Microsoft.SharePoint.Administration.TraceSeverity.Verbose, logEntry, new Guid());
            }
        }

        // Source: http://msdn.microsoft.com/en-us/library/ee538252.aspx (enhanced with LINQ and LoggingService)
        private static void HealthAnalyzerRules_Remove()
        {
            Assembly a = Assembly.GetExecutingAssembly();
            IDictionary<Type, Exception> exceptions = SPHealthAnalyzer.UnregisterRules(a);

            if (exceptions != null)
            {
                string logEntry = a.FullName;
                if (exceptions.Count == 0)
                {
                    logEntry += " All rules were unregistered.";
                }
                else
                {
                    logEntry += String.Join(", ", exceptions.Select(e => String.Format("Unregistration failed for type {0}. {1}", e.Key, e.Value.Message)).ToArray());
                }
                LoggingService.Write(LoggingService.Category_FeatureReceiver, Microsoft.SharePoint.Administration.TraceSeverity.Verbose, logEntry, new Guid());
            }
        }



        #endregion

    }
}
